package com.comp490.bullet;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Canvas;

import com.comp490.shooter.GameView;
import com.comp490.sound.SoundManager;
import com.comp490.sprite.EnemySprite;
import com.comp490.sprite.ShipSprite;

public class PlayerBulletContainer
{
    private int fcount;
    private int fireRate;
    private int next;
    private ShipSprite playerShip;
    private List<Bullet> bullets;
    private List<EnemySprite> enemies;
    private GameView gameView;

    public PlayerBulletContainer(int fr, ShipSprite pS, GameView g)
    {
        fcount = 0;
        fireRate = fr;
        playerShip = pS;
        next = 0;
        gameView = g;
        bullets = new ArrayList<Bullet>(40);
        for(int i = 0; i < 20; i++)
            bullets.add(new YellowPlayerBullet(-100, -100, 1, false));
    }

    public void setOnScreenEnemies(List<EnemySprite> enemies)
    {
        this.enemies = enemies;
    }

    public void updatePosition()
    {
        if(fcount++ % fireRate == 0 && playerShip.isActive())
        {
            Bullet bullet = bullets.get(next++);

            if(bullet.isActive())
                bullets.add(next, new YellowPlayerBullet(playerShip.getTipX(),
                        playerShip.getTipY(), 1, true));
            else
            {
                bullet.setX(playerShip.getTipX());
                bullet.setY(playerShip.getTipY());
                bullet.setActive(true);
            }
            // sound efx played when ship fires bullet
            SoundManager.playSoundEfx(SoundManager.PLAYER_FIRE);
            next = next % bullets.size();
        }
        for(int i = 0; i < bullets.size(); i++)
        {
            bullets.get(i).setX(bullets.get(i).getX() + 6);

            if(bullets.get(i).isActive())
            {
                if(!bullets.get(i).boundsCheck(gameView))
                	bullets.get(i).setActive(false);
                else
                {
                	for(int j = 0; j< enemies.size(); j++)
                	{
                        if(enemies.get(j).isActive() && bullets.get(i).collisionCheck(enemies.get(j)))
                        {
                        	bullets.get(i).setActive(false);
                            enemies.get(j).hit(bullets.get(i).getDamage());
                        }
                	}
                }
            }
        }
    }

    public void draw(Canvas c)
    {
    	for(int i = 0; i < bullets.size(); i++)
    	{
            if(bullets.get(i).isActive())
            	bullets.get(i).draw(c);
    	}
    }
}
